package com.suke.czx.modules.performanceconfig.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suke.czx.common.utils.*;
import com.suke.czx.modules.performanceconfig.entity.BasePerformance;
import com.suke.czx.modules.performanceconfig.entity.PerformanceConfig;
import com.suke.czx.modules.performanceconfig.entity.SimulationParam;
import com.suke.czx.modules.performanceconfig.mapper.PerformanceConfigMapper;
import com.suke.czx.modules.performanceconfig.service.PerformanceConfigService;
import com.suke.czx.modules.performanceconfig.strategy.PerformanceCalculateStrategy;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 应用模块名称: 绩效参数
 * 代码描述: 绩效参数业务层
 * copyright: AUZAR ALL RIGHTS RESERVED
 * company: AUZAR
 *
 * @author: 颜米晨
 * @date: 2022/06/11 17:57
 */
@Service
@AllArgsConstructor
public class PerformanceConfigServiceImpl extends ServiceImpl<PerformanceConfigMapper, PerformanceConfig> implements PerformanceConfigService {

    private final PerformanceConfigMapper performanceConfigMapper;

    /**
     * 获取绩效年份及版本
     *
     * @return 获取绩效年份及版本map
     */
    @Override
    public Map<String, Object> yearVersion() {
        // 结果map
        Map<String, Object> dataMap = new HashMap<>();
        // 已有年份和版本map
        List<Map<String, Object>> actualList = new ArrayList<>();
        // 下一可用年份版本map
        Map<String, Object> nextMap = new HashMap<>();
        // 当年年份
        String thisYear = StrUtil.toString(Calendar.getInstance().get(Calendar.YEAR));
        dataMap.put(FieldConstant.ACTUAL_YEAR_VERSION, actualList);
        dataMap.put(FieldConstant.NEXT_YEAR_VERSION, nextMap);
        // 查询数据库已有年份和版本
        Map<String, Map<String, String>> yearVersionMap = performanceConfigMapper.yearVersion();
        if (MapUtil.isEmpty(yearVersionMap)) {
            nextMap.put(FieldConstant.YEAR, thisYear);
            nextMap.put(FieldConstant.VERSION, 1);
            return dataMap;
        }
        yearVersionMap.forEach((k, v) -> {
            Map<String, Object> actualMap = new HashMap<>();
            actualMap.put(FieldConstant.YEAR, k);
            actualMap.put(FieldConstant.VERSION, Arrays.stream(StrUtil.split(v.get(FieldConstant.VERSION), CommonConstant.COMMA))
                    .map(Integer::valueOf).collect(Collectors.toList()));
            actualList.add(actualMap);
        });
        if (yearVersionMap.containsKey(thisYear) && StrUtil.isNotBlank(yearVersionMap.get(thisYear).get(FieldConstant.VERSION))) {
            nextMap.put(FieldConstant.YEAR, thisYear);
            String[] versionArr = StrUtil.split(yearVersionMap.get(thisYear).get(FieldConstant.VERSION), CommonConstant.COMMA);
            nextMap.put(FieldConstant.VERSION, Integer.valueOf(versionArr[versionArr.length - 1]) + 1);
        } else {
            nextMap.put(FieldConstant.YEAR, thisYear);
            nextMap.put(FieldConstant.VERSION, 1);
        }
        return dataMap;
    }

    /**
     * 保存绩效
     * @param performanceConfig 绩效参数实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePerformanceConfig(PerformanceConfig performanceConfig) {
        // 查询该年份版本下是否已有绩效配置的毛利率去除率
        List<BigDecimal> marginRemovalRateList = performanceConfigMapper.searchMarginRemovalRate(performanceConfig.getYear(),
                performanceConfig.getVersion());
        if (ListUtil.isEmpty(marginRemovalRateList) && performanceConfig.getMarginRemovalRate() == null) {
            throw new RuntimeException(performanceConfig.getYear() + "年份" + performanceConfig.getVersion() + "版本绩效参数毛利率去除率缺失,新增失败");
        }
        // 优先使用数据库年份下该版本已有毛利率去除率,否则取客户端传入的毛利率去除率
        performanceConfig.setMarginRemovalRate(!ListUtil.isEmpty(marginRemovalRateList) ? marginRemovalRateList.get(0)
                : performanceConfig.getMarginRemovalRate());
        // 查询该年份版本下是否已有绩效配置的备注
        List<String> noteList = performanceConfigMapper.searchNote(performanceConfig.getYear(),
                performanceConfig.getVersion());
        // 优先使用数据库年份下该版本已有备注,否则取客户端传入的备注
        performanceConfig.setNote(!ListUtil.isEmpty(noteList) ? noteList.get(0) : performanceConfig.getNote());
        save(performanceConfig);
    }

    /**
     * 批量更新同一年份版本下的毛利率去除率和备注
     * @param performanceConfig 绩效参数实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateMarginRemovalRateAndNote(PerformanceConfig performanceConfig) {
        performanceConfigMapper.updateMarginRemovalRateAndNote(performanceConfig.getYear(), performanceConfig.getVersion(),
                performanceConfig.getMarginRemovalRate(), performanceConfig.getNote());
        return R.ok();
    }

    /**
     * 复制绩效配置参数
     * @param performanceConfig 绩效参数
     * @return VO
     */
    @Override
    public R copyPerformanceConfig(PerformanceConfig performanceConfig) {
        // 根据年份及版本查询绩效参数数据集
        QueryWrapper<PerformanceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .eq(FieldConstant.DEL_FLG, CodeConstant.NOT_DEL)
                .eq(!StrUtil.isBlankIfStr(performanceConfig.getYear()), FieldConstant.YEAR, performanceConfig.getYear())
                .eq(!StrUtil.isBlankIfStr(performanceConfig.getVersion()), FieldConstant.VERSION, performanceConfig.getVersion());
        List<PerformanceConfig> dataList = list(queryWrapper);
        if (ListUtil.isEmpty(dataList)) {
            return R.error("该年份版本绩效参数为空");
        }
        // 查询该年份下现有最大版本号
        Integer maxVersion = performanceConfigMapper.getMaxVersionByYear(performanceConfig.getYear());
        Integer newVersion = maxVersion != null ? (maxVersion + 1) : 1;
        dataList.forEach(p -> {
            p.setPerformanceConfigId(null);
            p.setVersion(newVersion);
            p.setCreator(performanceConfig.getCreator());
            p.setCreateTime(performanceConfig.getCreateTime());
            p.setUpdater(null);
            p.setUpdateTime(null);
            save(p);
        });
        return R.ok();
    }

    /**
     * 绩效模拟计算
     *
     * @param simulationParam 绩效计算参数实体
     * @return VO
     */
    @Override
    public R simulation(SimulationParam simulationParam) {
        // 根据绩效参数id查询绩效参数
        PerformanceConfig performanceConfig = getById(simulationParam.getPerformanceConfigId());
        if (performanceConfig == null) {
            return R.error("绩效参数不存在");
        }
        if (performanceConfig.getJob1() == null || performanceConfig.getJob2() == null) {
            return R.error("绩效参数错误,无法计算");
        }
        BasePerformance basePerformance = PerformanceCalculateStrategy.calculatePerformance(simulationParam, performanceConfig);
        return R.ok().setData(basePerformance);
    }

}
